import React from 'react';
import {
	Table,
	Divider,
	Icon,
	Popconfirm,
	message,
	Form,
	Modal,
	Button,
	Input,
	Radio,
	Pagination
} from 'antd';

import $ from 'jquery';


const FormItem = Form.Item;

//定义模态框
const CreateForm = Form.create()(props => {
	const {
		modalVisiable,
		onAdd,
		onShowModal,
		formValues,
		form
	} = props;


	//触发onOk事件时，首先校验，然后提交数据
	const onHandle = () => {
		form.validateFields((err, values) => {
			if (err) {
				return;
			}
			console.log('Received values of form: ', values);
			form.resetFields(); //重置输入域
			// onAdd(JSON.stringify(values));
			onAdd(values);

		});
	}

	return (
		<Modal
		visible={modalVisiable}
		title="销售信息"
		okText="确定"
		onCancel={()=>onShowModal(false)}
		onOk={onHandle}
		>
     	<FormItem labelCol={{span:5}} wrapperCol={{span:15}}>
		{form.getFieldDecorator('id',{
			initialValue:formValues.id
		})(<Input placeholder="ID" type="hidden"/>)}
		</FormItem>
		<FormItem labelCol={{span:5}} wrapperCol={{span:15}}>
		{form.getFieldDecorator('month',{
			rules: [{ required: true, message: '请输入月份!' }],
			initialValue:formValues.month
		})(<Input placeholder="月份" />)}
		</FormItem>
		<FormItem labelCol={{span:5}} wrapperCol={{span:15}}>
		{form.getFieldDecorator('sales',{
			rules: [{ required: true, message: '请输入销售额!' }],
			initialValue:formValues.sales
		})(<Input placeholder="销售额" />)}
		</FormItem>

		</Modal>
	)
})

export default class SalesDetailEdit extends React.Component {

	constructor(props) {
		super(props);
		this.state = {
			itemList: [],
			modalVisiable: false,
			edtFlag: -1,
			loading: false,
			total: 0
		}
	}

	/**
	 * 在组件首次挂载的时候执行从后台获取数据，只执行一次
	 * 
	 */
	componentDidMount() {
		$.getJSON('http://localhost:8080/find/1/10', function(data) {
			this.setState({
				itemList: data.list,
				total: data.total
			});
			// console.log(this.state.itemList);
		}.bind(this))

	}

	// 删除方法
	onDelete = (index) => {
		console.log(index);
		var item_id = this.state.itemList[index].id;

		$.getJSON("http://localhost:8080/delete/" + item_id, function(data) {
			if (data.code == 1) {
				const dataSource = [...this.state.itemList];
				dataSource.splice(index, 1); //splice从index行删除，1代表删除几行
				this.setState({
					itemList: dataSource
				});
				message.success(data.msg);
			} else {
				message.error(data.msg);
			}

		}.bind(this))
	}

	//控制模态框显示
	onShowModal = (flag, index = -1) => {
		console.log(flag, index);
		this.setState({
			modalVisiable: flag,
			edtFlag: index
		})
	}

	//添加方法
	onAdd = (fields) => {
		console.log(fields);
		let url = "http://localhost:8080/";
		//判断是新增还是修改
		if (this.state.edtFlag == -1) {
			url += "save";
		} else {
			url += "update";
		}

		//调用接口
		$.getJSON(url, fields, function(data) {
			//1、重新获取数据
			//2、修改原来的数据(演示，修改页面数据按此方法）
			if (data.code == 1) {
				let {
					itemList,
					edtFlag
				} = this.state;
				let dataSource = [];
				if (edtFlag == -1) { //新增
					dataSource = [data.items, ...this.state.itemList];

				} else { //修改
					itemList[edtFlag] = data.items;
					dataSource = [...this.state.itemList];
				}

				this.setState({
					itemList: dataSource,
					modalVisiable: false
				});
				message.success(data.msg);
			} else {
				message.error(data.msg);
			}

		}.bind(this))

	}


	//分页点击事件
	getPages = (page, pageSize) => {
		this.setState({
			loading: true,
			page: page
		})
		$.getJSON('http://localhost:8080/find/' + page + '/' + pageSize, function(data) {
			this.setState({
				itemList: data.list,
				total: data.total
			});
		}.bind(this)).then(() => {
			this.setState({
				loading: false
			})
		})
	}



	render() {

		const dataSource = this.state.itemList;

		const columns = [{
			title: 'ID',
			dataIndex: 'id',
			key: 'id',
		}, {
			title: '月份',
			dataIndex: 'month',
			key: 'month',
		}, {
			title: '销售额',
			dataIndex: 'sales',
			key: 'sales',
		}, {
			title: '创建时间',
			dataIndex: 'createtime',
			key: 'createtime',
		}, {
			title: '操作',
			key: 'operation',
			render: (text, record, index) => (
				<span>
					<a href="javascript:;" onClick={()=>this.onShowModal(true,index)}><Icon type="edit"/>编辑</a>
					<Divider type="vertical" />

					<Popconfirm title="你确定要删除这个销售记录么?" onConfirm={this.onDelete.bind(this,index)} 
					onCancel={function(){message.error('已取消')}} okText="Yes" cancelText="No">
					<a href="javascript:;"><Icon type="delete"/>删除</a>
					</Popconfirm>
					</span>
			),
		}];

		return (
			<div>
				<Button icon="plus" type="primary" onClick={()=>{this.onShowModal(true)}}>
				新建
				</Button>

			{/* 判断是否是新增还是修改，如果是修改（！=-1）就把对应的数据传递过去 */}
			<CreateForm
			modalVisiable = {this.state.modalVisiable}
			onShowModal={this.onShowModal}
			onAdd={this.onAdd}				
			formValues={this.state.edtFlag!=-1?this.state.itemList[this.state.edtFlag]:{}}
			/>

		{/*	<Table dataSource={dataSource} columns={columns} rowKey="id"/>*/}			

			<Table 
		        dataSource={dataSource} 
		        columns={columns} 
		        rowKey='id' 
		        pagination={false} 
		        bordered={false} 
		        loading={this.state.loading}
	        />
	        <Pagination defaultCurrent={1} total={this.state.total} onChange={this.getPages} style={{marginTop:"20px",float:"right"}}/>

			</div>
		);
	}
}